<template>
  <div class="user-management-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户名"
              style="width: 200px; margin-right: 10px"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select
              v-model="filterRole"
              placeholder="筛选角色"
              style="width: 120px; margin-right: 10px"
              clearable
              @change="handleSearch"
            >
              <el-option label="管理员" value="admin" />
              <el-option label="普通用户" value="user" />
            </el-select>
            <el-select
              v-model="filterStatus"
              placeholder="筛选状态"
              style="width: 120px"
              clearable
              @change="handleSearch"
            >
              <el-option label="正常" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </div>
        </div>
      </template>

      <el-table
        :data="users"
        v-loading="loading"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="row.role === 'admin' ? 'danger' : 'info'">
              {{ row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="phone" label="电话" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="handleChangeRole(row)"
            >
              修改角色
            </el-button>
            <el-button
              :type="row.status === 'active' ? 'danger' : 'success'"
              size="small"
              @click="handleChangeStatus(row)"
            >
              {{ row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="用户详情" width="600px">
      <el-descriptions :column="2" border v-if="selectedUser">
        <el-descriptions-item label="用户ID">{{ selectedUser.id }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ selectedUser.username }}</el-descriptions-item>
        <el-descriptions-item label="角色">
          <el-tag :type="selectedUser.role === 'admin' ? 'danger' : 'info'">
            {{ selectedUser.role === 'admin' ? '管理员' : '普通用户' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="selectedUser.status === 'active' ? 'success' : 'danger'">
            {{ selectedUser.status === 'active' ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ selectedUser.email || '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="电话">{{ selectedUser.phone || '未设置' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ selectedUser.createdAt }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog v-model="roleDialogVisible" title="修改角色" width="400px">
      <el-form :model="roleForm" label-width="100px">
        <el-form-item label="当前角色">
          <el-tag :type="selectedUser?.role === 'admin' ? 'danger' : 'info'">
            {{ selectedUser?.role === 'admin' ? '管理员' : '普通用户' }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新角色">
          <el-select v-model="roleForm.role" style="width: 100%">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmChangeRole">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { userAPI } from '../services/api'

const loading = ref(false)
const users = ref([])
const searchKeyword = ref('')
const filterRole = ref('')
const filterStatus = ref('')
const selectedUser = ref(null)
const detailDialogVisible = ref(false)
const roleDialogVisible = ref(false)
const selectedRows = ref([])

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

const roleForm = reactive({
  role: ''
})

const fetchUsers = async () => {
  loading.value = true
  try {
    const response = await userAPI.getUserList({
      keyword: searchKeyword.value || undefined,
      role: filterRole.value || undefined,
      status: filterStatus.value || undefined,
      page: pagination.page,
      size: pagination.size,
      sort: 'createdAt',
      order: 'desc'
    })
    users.value = response.content || []
    pagination.total = response.total || 0
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchUsers()
}

const handleSizeChange = () => {
  pagination.page = 1
  fetchUsers()
}

const handlePageChange = () => {
  fetchUsers()
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleViewDetail = async (user) => {
  try {
    const response = await userAPI.getUserById(user.id)
    selectedUser.value = response.user
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '获取用户详情失败')
  }
}

const handleChangeRole = (user) => {
  selectedUser.value = user
  roleForm.role = user.role
  roleDialogVisible.value = true
}

const handleConfirmChangeRole = async () => {
  if (!selectedUser.value) return
  
  try {
    await userAPI.updateUserRole(selectedUser.value.id, roleForm.role)
    ElMessage.success('角色修改成功')
    roleDialogVisible.value = false
    await fetchUsers()
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '角色修改失败')
  }
}

const handleChangeStatus = async (user) => {
  const newStatus = user.status === 'active' ? 'inactive' : 'active'
  const action = newStatus === 'active' ? '启用' : '禁用'
  
  try {
    await ElMessageBox.confirm(`确定要${action}用户 ${user.username} 吗？`, `确认${action}`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await userAPI.updateUserStatus(user.id, newStatus)
    ElMessage.success(`${action}成功`)
    await fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || `${action}失败`)
    }
  }
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-management-container {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

